﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using TY.Utilities;
using CefSharp;
using CefSharp.WinForms;
using CCWin;
using System.Threading;
using System.Threading.Tasks;



namespace TY_75Stability.WinApp
{
    public partial class MainCefForm : CCSkinMain
    {
        #region 全局变量
        //CEFSharp对象
        private ChromiumWebBrowser webBrowser = null;
        private CVCamera cvCamera = null;
        #endregion
        public MainCefForm()
        {
            var setting = new CefSharp.CefSettings();
            setting.CefCommandLineArgs.Add("--allow-file-access-from-files", "1");
            setting.CefCommandLineArgs.Add("--disable-web-security", "1");
            CefSharp.Cef.Initialize(setting, true, false);
            InitializeComponent();
        }
        SysControl sysControl;
        private void MainCefForm_Load(object sender, EventArgs e)
        {


            webBrowser = new ChromiumWebBrowser(Application.StartupPath + @"\UI\Page\Login.html");

            this.Controls.Add(webBrowser);
            webBrowser.Visible = false;
            webBrowser.FrameLoadEnd += WebBrowser_FrameLoadEnd;

            MyService myService = new MyService(webBrowser);
            myService.InitCameraEvent += MyService_InitCameraEvent;
            myService.ShowCameraEvent += MyService_ShowCameraEvent;
            myService.HideCameraEvent += MyService_HideCameraEvent;
            myService.StartRecordVideoEvent += MyService_StartRecordVideoEvent;
            myService.StopRecordVideoEvent += MyService_StopRecordVideoEvent;
            webBrowser.RegisterAsyncJsObject("myService", myService, false);

            sysControl = new SysControl();
            sysControl.SaveFileDialogEvent += SysControl_SaveFileDialogEvent;
            sysControl.GetVideoPathEvent += SysControl_GetVideoPathEvent;
            sysControl.SaveVideoPathEvent += SysControl_SaveVideoPathEvent;
            sysControl.SelectPathEvent += SysControl_SelectPathEvent;
            sysControl.MoveFormEvent += SysControl_MoveFormEvent;
            sysControl.CloseFormEvent += SysControl_CloseFormEvent;
            webBrowser.RegisterJsObject("sysControl", sysControl, false);

            //SvgDocument svgDoc;

            //// Create a MemoryStream from SVG string.
            //using (MemoryStream streamSvg = new MemoryStream(
            //  Encoding.UTF8.GetBytes(ReadHelper.ReadTxtFile("D:\\111111.txt"))))
            //{
            //    svgDoc = SvgDocument.Open<SvgDocument>(streamSvg);
            //}

            //svgDoc.Transforms = new SvgTransformCollection();
            //float scalar = (float)500 / (float)svgDoc.Width;
            //svgDoc.Transforms.Add(new SvgScale(scalar, scalar));
            //svgDoc.Width = new SvgUnit(svgDoc.Width.Type, svgDoc.Width * scalar);
            //svgDoc.Height = new SvgUnit(svgDoc.Height.Type, svgDoc.Height * scalar);
            //svgDoc.Draw().Save("D:\\233333.png", ImageFormat.Png);

        }

        private string SysControl_SaveVideoPathEvent(string arg)
        {
            ConfigNoCacheHelper.AppSettings("VideoPath", arg);
            return "ok";
        }

        private string SysControl_GetVideoPathEvent()
        {
            if (ConfigNoCacheHelper.AppSettings("VideoPath") == "")
            {
                return Application.StartupPath + @"\Resource\ExperimentVideo";
            }
            else
            {
                return ConfigNoCacheHelper.AppSettings("VideoPath");
            }
        }

        private string SysControl_SelectPathEvent()
        {
            string selectPath = "";
            this.Invoke(new Action(() =>
            {
                selectPath = SelectPath("选择保存视频路径");
            }));
            return string.IsNullOrEmpty(selectPath) ? "" : selectPath;
        }

        private void SysControl_CloseFormEvent()
        {
            this.Invoke(new Action(delegate
            {
                this.Close();
            }));
        }

        private void SysControl_MoveFormEvent()
        {
            //this.Invoke(new Action(delegate
            //{
            //    this.MoveForm();
            //}));
        }

        private string SysControl_SaveFileDialogEvent(string title, string defaultFileName)
        {
            string savePath = "";
            this.Invoke(new Action(delegate
            {
                savePath = SaveLocalFile(title, defaultFileName);

            }));
            return savePath;
        }

        private void MyService_HideCameraEvent()
        {
            this.Invoke(new Action(delegate
            {
                this.skinPictureBox1.Visible = false;
            }));
        }

        private void MyService_ShowCameraEvent()
        {
            this.Invoke(new Action(delegate
            {
                this.skinPictureBox1.Visible = true;
            }));
        }

        private void MyService_InitCameraEvent(string obj)
        {
            cvCamera = new CVCamera(string.Format("http://{0}:8080/?action=stream", obj));
            cvCamera.Start(skinPictureBox1);
        }

        private void MyService_StartRecordVideoEvent(string obj, int obj1)
        {
            var videoPath = sysControl.GetVideoPath() + string.Format(@"\{0}\{1}", obj, obj1);
            FileOpera.createPath(videoPath);
            this.Invoke(new Action(() =>
            {
                cvCamera.StartRecord(string.Format(@"{0}\{1}.avi", videoPath, Utils.GetRamCode()));
            }));

        }

        private void MyService_StopRecordVideoEvent()
        {

            this.Invoke(new Action(() =>
            {
                cvCamera.StopRecord();
            }));
        }

        private void WebBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {

            this.Invoke(new Action(() =>
            {
                pictureBox1.Visible = false;
                label1.Visible = false;
                webBrowser.Visible = true;
                webBrowser.Focus();
                //webBrowser.ShowDevTools();
            }));
        }
        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <returns></returns>
        public static string SelectPath(string desc)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = desc;
            if (path.ShowDialog() == DialogResult.OK)
            {
                return path.SelectedPath;
            }
            else
            {
                return "";
            }
        }
        private string SaveLocalFile(string title, string defaultFileName, string filter = "Excel文件|*.xlsx")
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = title;
            saveFileDialog.Filter = filter;
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = defaultFileName;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            else
            {
                return "";
            }
        }
        private void MainCefForm_FormClosing(object sender, FormClosingEventArgs e)
        {


        }

        private void MainCefForm_FormClosed(object sender, FormClosedEventArgs e)
        {

            webBrowser.Dispose();
            CefSharp.Cef.Shutdown();
            CefSharp.Cef.Shutdown();
            //webBrowser.ShowDevTools();
            if (cvCamera != null)
            {
                cvCamera.Stop();
            }
        }
    }
}
